package org.zh.home.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.zh.home.dao.IGroupDao;
import org.zh.home.entity.Column;
import org.zh.home.entity.Group;
import org.zh.home.entity.GroupColumn;
import org.zh.home.model.Operate;
import org.zh.home.model.Pager;
import org.zh.home.model.Query;
import org.zh.home.model.Separator;
import org.zh.home.service.IGroupService;
import org.zh.home.utils.StringUtils;

@Service
public class GroupService implements IGroupService {
	private IGroupDao groupDao;
	
	public IGroupDao getGroupDao() {
		return groupDao;
	}

	@Inject
	public void setGroupDao(IGroupDao groupDao) {
		this.groupDao = groupDao;
	}

	@Override
	public Pager<Group> find(String name) {
		List<Query> model = new ArrayList<Query>();
		if(StringUtils.isNotBlank(name)) {
			Query nq = new Query();
			nq.setName("name");
			nq.setOperate(Operate.EQ);
			nq.setSeparator(Separator.AND);
			nq.setValue(name);
			model.add(nq);
		}
		return groupDao.find(model);
	}

	@Override
	public void add(Group group,String columns) {
		if(StringUtils.isBlank(group.getName())) {
			throw new RuntimeException("分组名称不能为空");
		}
		group = groupDao.add(group);
		
		if(StringUtils.isNotBlank(columns)) {
			String[] cs = columns.trim().split(",");
			for(int i=0;i<cs.length;i++) {
				int cid = Integer.parseInt(cs[i]);
				Column column = (Column) groupDao.loadEntity(Column.class, cid);
				if(column == null) continue;
				GroupColumn gc = new GroupColumn();
				gc.setColumnId(column.getId());
				gc.setColumnName(column.getName());
				gc.setGroupId(group.getId());
				gc.setGroupName(group.getName());
				groupDao.addEntity(gc);
			}
		}
	}

	@Override
	public Group load(int id) {
		return groupDao.load(id);
	}

	@Override
	public void update(Group temp, String columns) {
		if(StringUtils.isBlank(temp.getName())) {
			throw new RuntimeException("分组名称不能为空");
		}
		Group group = groupDao.load(temp.getId());
		if(group != null) {
			group.setName(temp.getName());
		}
		groupDao.update(group);
		groupDao.deleteGroupColumn(group.getId());
		if(group!=null&&StringUtils.isNotBlank(columns)) {
			String[] cs = columns.trim().split(",");
			for(int i=0;i<cs.length;i++) {
				int cid = Integer.parseInt(cs[i]);
				Column column = (Column) groupDao.loadEntity(Column.class, cid);
				if(column == null) continue;
				GroupColumn gc = new GroupColumn();
				gc.setColumnId(column.getId());
				gc.setColumnName(column.getName());
				gc.setGroupId(group.getId());
				gc.setGroupName(group.getName());
			}
		}
	}

	@Override
	public void delete(int id) {
		Group temp = groupDao.load(id);
		if(temp == null) throw new RuntimeException("要删除的分组不存在");
		groupDao.deleteGroupColumn(id);
		groupDao.updateUserGroupRole(id);
		groupDao.delete(temp);
	}
}
